﻿import React from 'react';
import {connect} from 'react-redux'
import {Form, Table, DatePicker, message} from "antd/lib/index";
import supplierDetailService from 'containers/supplier-management/overview/supplier-detail/supplier-detail.service'
import moment from 'moment';
import {messages} from "share/common";
import errorMessage from "share/errorMessage";
import {Popover} from "antd";

class SyncData extends React.Component {
  constructor(props) {
    super(props);
    //初始化对象
    this.state = {
      loading: true,
      columns: [
        {
          title: messages('supplier.key170'/*成本中心号*/),
          dataIndex: 'corNum',
          width: '15%'
        },
        {
          title: messages('supplier.key171'/*开始日期*/),
          dataIndex: 'startDate',
          render: (value, record) => this.dateColumnsRender(record, 'startDate'),
          width: '25%'
        },
        {
          title: messages('common.end.date')/*结束日期*/,
          dataIndex: 'endDate',
          render: (value, record) => this.dateColumnsRender(record, 'endDate'),
          width: '25%'
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'manualSyncStatus',
          render: this.manualSyncStatusColumnsRender,
          width: '12%'
        },
        {
          title: messages('supplier.key628')/*状态说明*/,
          dataIndex: 'manualSyncStatusNote',
          render: (value, record) => this.manualSyncStatusNoteRender(value, record),
          width: '23%'
        }
      ],
      data: [],
      selectedRowKeys: [],//选中的keyID
      selectedRows: [], //选中的行信息
      dataStatusChange: false
    }
    //初始化数据获取
    this.getList();
  }

  componentDidMount() {
    //订阅事件绑定
  }

  componentWillReceiveProps() {
    //state状态改变、回调(此处react重绘严重,注意代码严谨性)

  }

  componentWillUnmount() {
    //订阅事件释放
  }

  //此处页面函数处理（数据获取=》业务处理=》事件操作）
  //star-数据获取
  getList() {
    if (!this.state.loading) {
      this.setState({loading: true})
    }
    supplierDetailService.queryHistoryData(this.props.supplierName).then(res => {
      this.setState({
        data: res.data.rows ? res.data.rows.tenantBankCardCfgList : [], loading: false
      })
    }).catch(e => {
      this.setState({loading: false})
      errorMessage(e.response);
    })
  }

  //end-数据获取
  //star-业务处理
  disabledDate = (date, record, dateType) => {
    let startDate = dateType === 'startDate' ? date : record.startDate;
    let endDate = dateType === 'endDate' ? date : record.endDate;
    if (startDate && endDate) {
      return !(endDate.isSameOrAfter(startDate) && startDate.isSameOrAfter(endDate.clone().add(-60, 'd')));
    }
    return false;
  }

  //检查用户是否信息输入完全
  checkUserIsConfirm() {
    let {selectedRows} = this.state;
    let checkUserIsNotConfirm = false;
    selectedRows && selectedRows.length > 0 ? selectedRows.map(item => {
      if (!item.startDate || !item.endDate) {
        checkUserIsNotConfirm = true
      }
    }) : checkUserIsNotConfirm = true;
    this.props.checkUserIsConfirm(checkUserIsNotConfirm)
  }

  //end-业务处理
  //star-事件操作
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({selectedRowKeys, selectedRows}, () => {
      this.checkUserIsConfirm();
    });
  }
  dateColumnsRender = (record, dateType) => {
    let {selectedRowKeys} = this.state;
    let disabled = !~selectedRowKeys.indexOf(record.id);
    return <DatePicker
      disabledDate={(current) => this.disabledDate(current, record, dateType)}
      disabled={disabled} onChange={(date) => this.selectDateOnChange(date, record, dateType)}/>;
  }
  manualSyncStatusColumnsRender = (value) => {
    let element = typeof value === 'number' ? [messages('supplier.key172'/*可同步*/), messages('supplier.key173'/*同步中*/),
      messages('supplier.key174'/*未知*/), messages('supplier.key175'/*同步失败*/)][value] : messages('supplier.key174'/*未知*/);
    return (
      <Popover content={element}>{element}</Popover>
    );
  }
  manualSyncStatusNoteRender = (value, record) => {
    //接口返回的syncFaildMsg可能会为null，为null时失败原因显示为空
    let element = (record.manualSyncStatus === 3) ? ((record.syncFaildMsg == null) ? '' : record.syncFaildMsg) : '';
    return (
      <Popover content={element}>{element}</Popover>
    );
  }
  selectDateOnChange = (date, record, dateType) => {
    record[dateType] = date;
    this.checkUserIsConfirm();
  }
  confirmSyncData = () => {
    let {selectedRows, loading} = this.state;
    if (loading) {
      return;
    }
    this.setState({loading: true})
    let params = [];
    selectedRows.map(item => {
      params.push({
        id: item.id,
        corNum: item.corNum,
        startDate: item.startDate.format('YYYY-MM-DD'),
        endDate: item.endDate.format('YYYY-MM-DD')
      });
    })
    supplierDetailService.addQueryHistoryData(this.props.supplierName, params).then(res => {
      message.success(messages('supplier.key176'/*操作成功，正在同步历史数据。*/));
      this.setState({loading: false, dataStatusChange: true})
      this.props.handleModalCancel();
    }).catch(e => {
      this.setState({loading: false})
      errorMessage(e.response);
    })
  }

  //end-事件操作
  render() {
    const {loading, columns, data, selectedRowKeys} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true
    };
    return (<div>
      <Table
        loading={loading}
        rowKey={'id'}
        pagination={false}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        size="middle"
        bordered/>
    </div>)
  }
}

SyncData.propsType = {
  showModal: React.PropTypes.bool, //显示Modal
  supplierName: React.PropTypes.string, //显示Modal
  checkUserIsConfirm: React.PropTypes.func, //检查用户信息是否输入完全
  handleModalCancel: React.PropTypes.func,
}
SyncData.defaultProps = {
  showModal: false,
  checkUserIsConfirm: () => {
  },
  handleModalCancel: () => {
  }
}
SyncData.contextTypes = {
  router: React.PropTypes.object
};


function mapStateToProps(state) {
  return {}
}

const WrappedSyncData = Form.create()(SyncData);

export default connect(mapStateToProps)(WrappedSyncData)
